import http from '@/utils/http'
import { encrypt } from '@/utils/cryptojs-aes'

// 登录
export async function apiLogin(args = {}) {
  const url = '/user/login'
  const params = {
    username: '',
    password: '',
    ...args,
  }

  // 密码根据用户名来加密
  params.password = encrypt(params.password, params.username)

  const { data } = await http.post(url, params)
  return data
}

// 自动尝试登录
export async function apiAutoLogin() {
  const url = '/user/auto-login'
  const { data } = await http.get(url, {}, { useError: false })
  return data
}

// 登出
export async function apiLogout() {
  const url = '/user/logout'
  await http.post(url, {}, { useError: false })
}

// 注册
export async function apiSignUp(args = {}) {
  const url = '/user/sign-up'
  const params = {
    username: '',
    password: '',
    nickname: '',
    avatar: '',
    gender: 'unknow',
    cv: '',
    desc: '',
    ...args,
  }

  // 密码根据用户名来加密
  params.password = encrypt(params.password, params.username)

  await http.post(url, params)
}

// 更新信息
export async function apiUpdateInfo(args = {}) {
  const url = '/user/update'
  const params = {
    nickname: '',
    avatar: '',
    gender: 'unknow',
    cv: '',
    desc: '',
    ...args,
  }

  await http.put(url, params)
}

// 修改密码
export async function apiSetPassword(args = {}) {
  const url = '/user/update-password'
  // 需要使用'username'来做key
  const { username, password, newPassword } = args
  const params = {
    password: encrypt(password, username),
    newPassword: encrypt(newPassword, username),
  }

  await http.put(url, params)
}

// 获取所有用户
export async function apiGetUsers() {
  const url = '/users'
  const { data = { list: [], total: 0 } } = await http.get(url)
  return data
}
